package com.momoauth.api_client.listener;

import com.momoauth.api_client.entity.Login_Log;
import com.momoauth.api_client.mapper.LoginLogMapper;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @author Wei
 * @date 2021/07/2021/7/24
 */
@Component
public class LoginListener {

    @Resource
    LoginLogMapper loginLogMapper;

    /**
     * 创建登录日志
     * @author Wei
     * @date 2021/7/24 15:27
     * @params obj
     * @params channel
     * @params message
     */
    @RabbitListener(queues = "createLoginLogQueue")
    public void createLoginLogQueue(@Payload Map obj, Channel channel, Message message) throws IOException {
        try {
            //接受参数
            String username = obj.get("username").toString();
            String loginIp = obj.get("loginIp").toString();
            String loginType = obj.get("loginType").toString();
            //构建参数
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Login_Log login_log = new Login_Log();
            login_log.setLoginUser(username); //登录用户
            login_log.setLoginTime(sdf.format(new Date())); //登录时间
            login_log.setLoginIp(loginIp); //登录IP
            login_log.setLoginType(Integer.parseInt(loginType)); //登录类型 1.电脑网页版
            loginLogMapper.insert(login_log);
            //确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("消费者收到消息并ACK返回: " + obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
            //否认消息
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
